package com.zsr.system.service.qw.impl;

import com.alibaba.fastjson2.JSONObject;

import com.zsr.common.core.redis.RedisCache;
import com.zsr.common.enums.qw.QwTaKeyEnum;
import com.zsr.common.exception.ServiceException;
import com.zsr.common.utils.http.OkHttpUtil;
import com.zsr.system.service.qw.IWechatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 荣
 * @date 2025/3/26 14:50
 */
@Service
@Slf4j
public class WechatServiceImpl implements IWechatService {

    @Resource
    private RedisCache redisCache;

    @Override
    public String getAccessToken(Integer count) {
        Boolean isHas = redisCache.hasKey("WECHAT_ACCESS_TOKEN");
        if (isHas) {
            return redisCache.getCacheObject("WECHAT_ACCESS_TOKEN");
        }

        if (count > 3) {
            return null;
        }
        Map<String, Object> params = new HashMap<>();

        params.put("corpid", QwTaKeyEnum.CORP_ID.getValue());
        params.put("corpsecret", QwTaKeyEnum.CORPSECRET.getValue());
        String response = OkHttpUtil.qwGet("https://qyapi.weixin.qq.com/cgi-bin/gettoken", params);

        JSONObject json = JSONObject.parseObject(response);

        if (json.get("access_token") != null) {
            String accessToken = json.getString("access_token");
            redisCache.setCacheObject("WECHAT_ACCESS_TOKEN", accessToken, json.getInteger("expires_in"), TimeUnit.SECONDS);
            return accessToken;
        }
        if (json.get("errmsg") != null) {
            log.info("错误信息：{}", json.getString("errmsg"));
            count++;
            getAccessToken(count);
        }
        return null;
    }

    @Override
    public JSONObject getStudentTag(String token, String groupId) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("access_token", token);
        JSONObject json = new JSONObject();
        ArrayList<String> groupIdList = new ArrayList<>();
        groupIdList.add(groupId);
        json.put("group_id", groupIdList);
        String response = OkHttpUtil.qwPost("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get_corp_tag_list", params, json);
        log.info("getStudentTag~response==" + response);
        return JSONObject.parseObject(response);
    }

    @Override
    public JSONObject getChatInfo(String token, String chatId, Integer needName) {
        if (needName == null) {
            needName = 0;
        }
        HashMap<String, Object> params = new HashMap<>();
        params.put("access_token", token);
        JSONObject json = new JSONObject();
        json.put("chat_id", chatId);
        json.put("need_name", needName);
        String response = OkHttpUtil.qwPost("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/get", params, json);
        return JSONObject.parseObject(response);
    }

    @Override
    public JSONObject getChatList(String token, String limit, String cursor) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("access_token", token);
        JSONObject json = new JSONObject();
        json.put("limit", limit);
        if (cursor != null) {
            json.put("cursor", cursor);
        }
        String response = OkHttpUtil.qwPost("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/groupchat/list", params, json);
        return JSONObject.parseObject(response);
    }

    @Override
    public JSONObject getCustomerList(String token, List<String> userIdList) {
        if (userIdList == null || userIdList.isEmpty()) {
            throw new ServiceException("userIdList不能为空");
        }
        HashMap<String, Object> params = new HashMap<>();
        params.put("access_token", token);
        JSONObject json = new JSONObject();
        json.put("userid_list", userIdList);
        String response = OkHttpUtil.qwPost("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/batch/get_by_user", params, json);
        return JSONObject.parseObject(response);
    }

    @Override
    public JSONObject getCustomerInfo(String token, String externalUserId) {
        if (externalUserId == null || externalUserId.isEmpty()) {
            throw new ServiceException("externalUserId不能为空");
        }
        HashMap<String, Object> params = new HashMap<>();
        params.put("access_token", token);
        params.put("external_userid", externalUserId);

        String response = OkHttpUtil.qwGet("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get", params);
        return JSONObject.parseObject(response);

    }

    @Override
    public JSONObject markTag(String token, String externalUserId, String userId, List<String> addTagList, List<String> removeTagList) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("access_token", token);
        JSONObject json = new JSONObject();
        json.put("external_userid", externalUserId);
        json.put("userid", userId);

        if (addTagList != null && !addTagList.isEmpty()) {
            json.put("add_tag", addTagList);
        }

        if (removeTagList != null && !removeTagList.isEmpty()) {
            json.put("remove_tag", removeTagList);
        }

        String response = OkHttpUtil.qwPost("https://qyapi.weixin.qq.com/cgi-bin/externalcontact/mark_tag", params, json);
        return JSONObject.parseObject(response);
    }
}
